<route lang="json5">
	{
	style: {
	navigationBarTitleText: '用户详情',
	},
	needLogin: true,
	layout: 'default',
	}
</route>

<template>
	<view class="user-detail-container p-4">
		<!-- 用户基本信息 -->
		<view class="bg-white rounded-lg p-4 mb-4">
			<view class="flex justify-between items-center">
				<view class="flex items-center flex-1">
					<view class="ml-4">
						<text class="text-lg font-medium">{{ description }}</text>
						<view class="text-gray-500 text-sm mt-1">
							<text>用户: {{username }}</text>
						</view>
						<view class="text-gray-500 mt-1">
							<text>手机号: {{ phone }}</text>
						</view>
					</view>
				</view>
				<wd-button type="error" size="small" @click="handleDeleteUser">删除用户</wd-button>
			</view>
		</view>

		<!-- 门禁卡列表 -->
		<view class="bg-white rounded-lg p-4 mb-4">
			<view class="flex justify-between items-center mb-4">
				<text class="text-lg font-bold flex-1">门禁卡管理</text>
				<wd-button type="primary" @click="showAddCardDialog">开卡</wd-button>
			</view>
			<wd-divider class="my-4"></wd-divider>
			<view v-if="gateCards.length > 0">
				<view v-for="card in gateCards" :key="card.id" class="card-item border-b border-gray-100 py-3">
					<view class="flex justify-between items-center">
						<view>
							<text class="font-medium">卡号: {{ card.cardId }}</text>
							<wd-tag class="ml-4" :type="card.status ? 'success' : 'danger'">
								{{ card.status ? '正常' : '禁用' }}
							</wd-tag>
							<view class="text-sm text-gray-500 mt-1">描述：{{ card.description ?? '-' }}</view>
							<view class="text-sm text-gray-500 mt-1">
								创建时间: {{ new Date(card.createdAt).toLocaleString() }}
							</view>
						</view>
						<view class="flex items-center">
							<wd-button type="error" class="ml-2" @click="handleDeleteCard(card)">删除</wd-button>
						</view>
					</view>
				</view>
			</view>
			<view v-else class="text-center py-8 text-gray-500">暂无门禁卡</view>
		</view>

		<!-- 门禁权限列表 -->
		<view class="bg-white rounded-lg p-4">
			<view class="flex justify-between items-center mb-4">
				<text class="text-lg font-bold flex-1">门禁权限</text>
			</view>
			<wd-divider class="my-4"></wd-divider>
			<view v-if="devices.length > 0">
				<view v-for="device in devices" :key="device.id" class="card-item border-b border-gray-100 py-3">
					<view class="flex justify-between items-center">
						<view class="flex-1">
							<text class="font-medium">{{ device.deviceName }}</text>
						</view>
						<wd-button v-if="hasPermission(device.id)" type="error" size="small"
							@click="() => handlePermissionChange(device, false)">
							撤销授权
						</wd-button>
						<wd-button v-else type="primary" size="small"
							@click="() => handlePermissionChange(device, true)">
							授予权限
						</wd-button>
					</view>
				</view>
			</view>
			<view v-else class="text-center py-8 text-gray-500">暂无门禁设备</view>
		</view>

		<!-- 添加门禁卡弹窗 -->
		<wd-popup v-model="showDialog" position="bottom">
			<view class="p-4">
				<view class="text-lg font-bold mb-4">添加门禁卡</view>
				<view class="text-red-500 text-lg font-bold mb-4">在单元门门口刷空白卡(1分钟内有效)，会自动填到下方卡号输入框</view>
				<wd-input v-model="newCardId" label="卡号" placeholder="请输入门禁卡号" class="mb-4" required />
				<wd-calendar v-model="endDate" label="日期选择" />
				<view class="flex justify-end mt-10 mb-20">
					<wd-button @click="showDialog = false" class="mr-2">取消</wd-button>
					<wd-button type="primary" @click="handleAddCard">确认</wd-button>
				</view>
			</view>
		</wd-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, onMounted } from 'vue'
	import { useUserStore } from '@/store'
	import {
		getGateCardListAPI,
		createGateCardAPI,
		deleteGateCardAPI,
		getCommunityUserStatusAPI,
	} from '@/service/gateCard'
	import type { components } from '@/types/ApiInterface'
	import dayjs from 'dayjs'
	import { deleteCommunityUserAPI } from '@/service/iam'
	import {
		getAllGateDevicesAPI,
		createGatePermissionAPI,
		deleteGatePermissionAPI,
	} from '@/service/gateDevice'

	import { getGateAccessLogListAPI } from '@/service/gateAccessLogApi'

	const userStore = useUserStore()
	const communityId = userStore.currentCommunity?.community.id
	const username = ref('')
	const description = ref('')
	const phone = ref('')
	const userId = ref('')
	const gateCards = ref<components['schemas']['GateCardListResponse'][]>([])
	const endDate = ref<number | null>(null)
	const showDialog = ref(false)
	const newCardId = ref('')
	const id = ref('')
	const permissions = ref<components['schemas']['GatePermissionListResponse'][]>([])
	const devices = ref<components['schemas']['GateDeviceFindAllResponse'][]>([])

	onLoad((options) => {
		console.log(options);
		if (options.id) {
			id.value = options.id
			username.value = options.username
			description.value = options.description
			phone.value = options.phone
			userId.value = options.userId
		}
	})


	// 仅存储最新一条数据的 cardId
	const latestCardId = ref<string | null>(null)

	// 用于存储 setInterval 的返回值，方便在组件卸载时清除定时器
	let timerId : number | undefined

	// 获取门禁访问记录列表
	const fetchGateAccessLog = async () => {
		// 当前时间
		const now = dayjs().format('YYYY-MM-DD HH:mm:ss')
		// 当前时间减去 60 秒
		const sixtySecondsBefore = dayjs().subtract(60, 'second').format('YYYY-MM-DD HH:mm:ss')
		  const page = 1
		  const pageSize = 1
		  const description = '卡片未绑定用户'
		
		try {
			  // 因为需要多次同名参数（accessTime），可以手动写两条
			const queryString = 
			    `page=${page}` +
			    `&pageSize=${pageSize}` +
			    `&description=${encodeURIComponent(description)}` +
			    `&communityId=${communityId}` +
			    `&accessTime=${encodeURIComponent(sixtySecondsBefore)}` + 
			    `&accessTime=${encodeURIComponent(now)}`
			
			const res = await getGateAccessLogListAPI(queryString)

			// 如果后端返回的数据是数组，直接取数组的第一项（因为只请求1条）
			latestCardId.value = res.data?.list?.[0]?.cardId ?? null
			if (latestCardId.value != null) {
				newCardId.value = latestCardId.value
			}
		} catch (error) {
			uni.showToast({
				title: '获取门禁访问记录失败',
				icon: 'error',
			})
		}
	}

	// 获取用户门禁卡列表
	const getGateCards = async () => {
		try {
			const res = await getCommunityUserStatusAPI({
				id: id.value,
			})
			gateCards.value = res.data.gateCard
			permissions.value = res.data.permissions
			console.log(res.data.permissions)
		} catch (error) {
			uni.showToast({
				title: '获取数据失败',
				icon: 'error',
			})
		}
	}

	// 获取所有门禁设备
	const getDevices = async () => {
		try {
			const res = await getAllGateDevicesAPI({
				communityId,
			})
			devices.value = res.data
		} catch (error) {
			uni.showToast({
				title: '获取设备列表失败',
				icon: 'error',
			})
		}
	}

	// 显示添加门禁卡弹窗
	const showAddCardDialog = () => {
		newCardId.value = ''
		showDialog.value = true
	}

	// 添加门禁卡
	const handleAddCard = async () => {
		if (!newCardId.value) {
			uni.showToast({
				title: '请输入卡号',
				icon: 'none',
			})
			return
		}

		try {
			await createGateCardAPI({
				cardId: newCardId.value,
				userId: userId.value,
				communityUserStatusId: id.value,
				status: true,
				endDate:
					endDate.value !== null && endDate.value !== undefined
						? dayjs(endDate.value).toISOString()
						: null,
			})

			uni.showToast({
				title: '添加成功',
				icon: 'success',
			})
			showDialog.value = false
			getGateCards()
		} catch (error) {
			uni.showToast({
				title: '添加失败',
				icon: 'error',
			})
		}
	}

	// 删除门禁卡
	const handleDeleteCard = async (card : components['schemas']['GateCardListResponse']) => {
		uni.showModal({
			title: '提示',
			content: '确定要删除该门禁卡吗？',
			success: async (res) => {
				if (res.confirm) {
					try {
						await deleteGateCardAPI({
							id: card.id,
						})
						uni.showToast({
							title: '删除成功',
							icon: 'success',
						})
						getGateCards()
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'error',
						})
					}
				}
			},
		})
	}

	// 添加删除用户方法
	const handleDeleteUser = () => {
		uni.showModal({
			title: '提示',
			content: '确定要删除该用户吗？删除后将无法恢复！',
			success: async (res) => {
				if (res.confirm) {
					try {
						await deleteCommunityUserAPI(id.value)
						uni.showToast({
							title: '删除成功',
							icon: 'success',
						})
						// 返回上一页
						uni.navigateBack()
					} catch (error) {
						uni.showToast({
							title: '删除失败',
							icon: 'error',
						})
					}
				}
			},
		})
	}

	// 检查用户是否有某个设备的权限
	const hasPermission = (deviceId : string) => {
		return permissions.value.some((p) => {
			console.log(unref(p.deviceId), deviceId)
			if (unref(p.deviceId) === deviceId) {
				console.log('match')
				return true
			}
			return false
		})
	}

	// 处理权限变更
	const handlePermissionChange = async (
		device : components['schemas']['GateDeviceFindAllResponse'],
		value : boolean,
	) => {
		try {
			if (value) {
				// 添加权限
				await createGatePermissionAPI({
					deviceId: device.id,
					userId: userId.value,
					communityId: communityId!,
					status: true,
					communityUserStatusId: id.value,
				})
			} else {
				// 删除权限
				const permission = permissions.value.find(
					(p) =>
						p.deviceId === device.id && p.userId === userId.value && p.communityId === communityId,
				)
				if (permission) {
					await deleteGatePermissionAPI({
						id: permission.id,
					})
				}
			}

			// 刷新权限列表
			await getGateCards()

			uni.showToast({
				title: value ? '添加权限成功' : '移除权限成功',
				icon: 'success',
			})
		} catch (error) {
			uni.showToast({
				title: value ? '添加权限失败' : '移除权限失败',
				icon: 'error',
			})
		}
	}

	onMounted(() => {
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const userId = (currentPage as any).$page?.options?.id

		if (userId) {
			getGateCards()
			getDevices()
		}

		// 每隔 60 秒请求一次
		timerId = setInterval(() => {
			fetchGateAccessLog()
		}, 6000) as unknown as number


	})
	onUnmounted(() => {
		// 清除定时器，避免组件卸载后依旧发请求
		if (timerId) {
			clearInterval(timerId)
		}
	})
</script>

<style lang="scss" scoped>
	.user-detail-container {
		overflow-y: scroll;
		background-color: #f8f8f8;
	}

	.card-item {
		&:last-child {
			border-bottom: none;
		}
	}
</style>